//
//  UserColleagueViewController.m
//  XinKaiFa55like
//
//  Created by junseek on 2017/3/26.
//  Copyright © 2017年 55like lj. All rights reserved.
//

#import "UserColleagueViewController.h"
#import "RHTableView.h"
#import "UserColleagueTableViewCell.h"
#import "SearchViewController.h"
#import "SelectWebUrlViewController.h"

@interface UserColleagueViewController (){
    RHTableView *table_user;
    NSMutableArray *arrayOriginal;
    NSMutableArray *arForTable;
    NSInteger tempRow;
}

@end

@implementation UserColleagueViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    NSDictionary *dTmp=[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"data" ofType:@"plist"]];
    arrayOriginal=[NSMutableArray new];
    arForTable=[NSMutableArray new];
   
    
    UISearchBar *txtSearch;
    txtSearch= [[UISearchBar alloc] initWithFrame:CGRectMake(0, kTopHeight, kScreenWidth, 44)];
    //txtSearch.delegate=self;
    txtSearch.placeholder=@"搜索";
    [self.view addSubview:txtSearch];
    [txtSearch setBackgroundImage:[[Utility Share] imageFromColor:rgbGray rect:txtSearch.frame.size]];
    txtSearch.userInteractionEnabled=NO;
    UIButton *btnSearch=[RHMethods buttonWithFrame:txtSearch.frame title:nil image:nil bgimage:nil];
    [btnSearch addTarget:self action:@selector(searchButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btnSearch];
    
    [self initTabelViews];
    [self loadColleageueData];
   
}

-(void)updateDataRowsUniqueValue:(NSArray*)ar setArray:(NSMutableArray *)setArray{
    
    for(NSDictionary *dInner in ar ) {
        NSMutableDictionary *dic_temp=[[NSMutableDictionary alloc] initWithDictionary:dInner];
        NSArray *arInner=[dInner valueForKey:@"list"];
        if(arInner && [arInner count]>0){
            NSMutableArray *mutTempA=[NSMutableArray new];
            [self updateDataRowsUniqueValue:arInner setArray:mutTempA];
            [dic_temp setValue:mutTempA forKey:@"list"];
        }
        tempRow++;
        //唯一关键值
        [dic_temp setValue:[NSString stringWithFormat:@"row_%ld",tempRow] forKey:@"UniqueValue"];
        [setArray addObject:dic_temp];
        
        if (!arInner) {
            NSMutableDictionary *dicSeach=[[NSMutableDictionary alloc] initWithDictionary:dic_temp];
            [arrayOriginal addObject:dicSeach];
        }
        
    }
    
}


-(void)initTabelViews{
    table_user=[[RHTableView alloc]initWithFrame:CGRectMake(0, kTopHeight+44, kScreenWidth, kContentHeight-44)];
    [table_user showRefresh:NO LoadMore:NO];
    table_user.delegate = self;
    table_user.dataSource = self;
    [table_user setBackgroundColor:rgbGray];
    [table_user setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [self.view addSubview:table_user];
    [table_user setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
    [table_user registerClass:[UserColleagueTableViewCell class] forCellReuseIdentifier:@"UserColleagueTableViewCell"];
}
-(void)loadColleageueData{
//    //XKFV3usercontact
    krequestParam
    [NetEngine createPostAction:XKFV3usercontact withParams:dictparam onCompletion:^(id resData, BOOL isCache) {
        if ([[resData valueForJSONStrKey:@"status"] isEqualToString:@"200"]) {
            tempRow=0;
            [arForTable removeAllObjects];
            [self updateDataRowsUniqueValue:[[resData objectForJSONKey:@"data"] objectForJSONKey:@"list"] setArray:arForTable];
            [table_user reloadData];
        }else{
            [SVProgressHUD showImage:nil status:[resData valueForJSONStrKey:@"info"]];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [super backButtonClicked:nil];
            });
        }
    } onError:^(NSError *error) {
        [SVProgressHUD showImage:nil status:alertErrorTxt];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [super backButtonClicked:nil];
        });
    }];
}

#pragma mark button
-(void)searchButtonClicked{
    //
    SearchViewController *serach=[[SearchViewController alloc] init];
    serach.userInfo=@"colleague_search";
    CATransition *transition = [CATransition animation];
    transition.duration = 0.4;
    transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    serach.otherInfo=@{@"list":arrayOriginal,@"searchKey":@"输入同事姓名/部门名称"};//
    [self.navigationController.view.layer addAnimation:transition forKey:nil];
    [self.navigationController pushViewController:serach animated:NO];
}

#pragma mark table

// Customize the number of sections in the table view.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [arForTable count];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{    
    NSDictionary *dic=[arForTable objectAtIndex:indexPath.row];
    if ([dic objectForJSONKey:@"list"]) {
        return 44;
    }
    return 60;
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dic=[arForTable objectAtIndex:indexPath.row];
    UserColleagueTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"UserColleagueTableViewCell" forIndexPath:indexPath];
    [cell setValueForDictionary:dic indexPath:indexPath type:@""];
    return cell;
   
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSDictionary *d=[arForTable objectAtIndex:indexPath.row];
    
    if([d valueForKey:@"list"]) {
        NSArray *ar=[d valueForKey:@"list"];
        if ([ar count]==0) {
            [SVProgressHUD showImage:nil status:@"没有成员！"];
            return;
        }
        BOOL isAlreadyInserted=NO;
        
        for(NSDictionary *dInner in ar ){
            BOOL abool=NO;
            for (NSInteger i=0;i<[arForTable count];i++) {
                NSDictionary *dt=[arForTable objectAtIndex:i];
                if ([[dt valueForJSONStrKey:@"UniqueValue"] isEqualToString:[dInner valueForJSONStrKey:@"UniqueValue"]]) {
                    isAlreadyInserted=(i>0 && i!=NSIntegerMax);
                    if(isAlreadyInserted) {
                        abool=YES;
                        DLog(@"1");
                    };
                    DLog(@"2");
                    break;
                }
            }
            DLog(@"3");
            if (abool) {
                break;
            }
        }
        
        
//        for(NSDictionary *dInner in ar ){
//            NSInteger index=[arForTable indexOfObjectIdenticalTo:dInner];
//            isAlreadyInserted=(index>0 && index!=NSIntegerMax);
//            if(isAlreadyInserted) break;
//        }
        //修改
        NSMutableDictionary *dcTemp=[[NSMutableDictionary alloc] initWithDictionary:d];
        if (isAlreadyInserted) {
            [dcTemp setValue:@"0" forKey:@"select"];
        }else{
            [dcTemp setValue:@"1" forKey:@"select"];
        }
        [arForTable replaceObjectAtIndex:indexPath.row withObject:dcTemp];
        [table_user reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
        
        
        if(isAlreadyInserted) {
            [self miniMizeThisRows:ar];
        } else {
            NSUInteger count=indexPath.row+1;
            NSMutableArray *arCells=[NSMutableArray array];
            for(NSDictionary *dInner in ar ) {
                [arCells addObject:[NSIndexPath indexPathForRow:count inSection:0]];
                [arForTable insertObject:dInner atIndex:count++];
            }
            [tableView insertRowsAtIndexPaths:arCells withRowAnimation:UITableViewRowAnimationLeft];
        }
    }else{// if ([[d valueForJSONStrKey:@"num"] integerValue]==4)
        NSMutableDictionary *dicCard=[[NSMutableDictionary alloc] initWithDictionary:d];
        [dicCard setValue:[d valueForJSONStrKey:@"card"] forKey:@"url"];
        [dicCard setValue:[d valueForJSONStrKey:@"ids"] forKey:@"uid"];
        [dicCard setValue:NSStringFromClass([self class]) forKey:@"controller"];
        [self pushController:[SelectWebUrlViewController class] withInfo:@"shareCard" withTitle:@" " withOther:dicCard];
    }
}

-(void)miniMizeThisRows:(NSArray*)ar{
    
    for(NSDictionary *dInner in ar ) {
        NSArray *arInner=[dInner valueForKey:@"list"];
        if(arInner && [arInner count]>0){
            [self miniMizeThisRows:arInner];
        }
        for (int i=0;i<[arForTable count];i++) {
            NSDictionary *dt=[arForTable objectAtIndex:i];
            if ([[dt valueForJSONStrKey:@"UniqueValue"] isEqualToString:[dInner valueForJSONStrKey:@"UniqueValue"]]) {
                //移除
                [arForTable removeObjectAtIndex:i];
                [table_user deleteRowsAtIndexPaths:[NSArray arrayWithObject:
                                                    [NSIndexPath indexPathForRow:i inSection:0]]
                                  withRowAnimation:UITableViewRowAnimationRight];

                break;
            }
        }
        
//        //唯一关键值
//        if([arForTable containsObject:dInner]) {
//            [arForTable removeObjectIdenticalTo:dInner];
//            [table_user deleteRowsAtIndexPaths:[NSArray arrayWithObject:
//                                                    [NSIndexPath indexPathForRow:indexToRemove inSection:0]
//                                                    ]
//                                  withRowAnimation:UITableViewRowAnimationRight];
//        }
    }
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
